const shoppingDao = require('../dao/shoppingDao'),
  crypto = require("crypto"),
  http = require("http"),
  url = require("url"),
  log = require("../util/log"),
  zoroDB = require("../util/zoroDB"),
  app_secret = '9bb708f72f48d4728977a4b47ad90cd5';
var isFilling = false,
  reqObj = {
    v: '2.0',
    app_key: '23449940',
    partner_id: 'top-apitools',
    session: '6100010c4d584a656110f422c29983490ecc9eaebc3811265717161',
    format: 'json',
    sign_method: 'md5',
    fields: 'num_iid,title,pict_url,small_images,zk_final_price,volume,reserve_price',
    method: 'taobao.tbk.item.info.get'
  };

exports.start = () => {
  if (isFilling)
    return;
  isFilling = true;
  zoroDB.query('select * from shopping where pict_url is null or small_images is null or title is null or zk_final_price is null or volume is null', [], (err, rows, fields) => {
    if (err) {
      log(err)
      return
    }
    fillShopping(shoppings)
  })
}

function fillShopping(shoppings) {
  if (shoppings.length == 0) {
    isFilling = false;
    return
  }
  var shopping = shoppings[0];
  reqObj.num_iids = shopping.num_iid;
  var date = new Date(),
    sDate = date.getFullYear();
  sDate += '-'
  sDate += (date.getMonth() < 9 ? '0' : '') + (date.getMonth() + 1) + '-'
  sDate += (date.getDate() < 10 ? '0' : '') + date.getDate() + ' '
  sDate += (date.getHours() < 10 ? '0' : '') + date.getHours() + ':'
  sDate += (date.getMinutes() < 10 ? '0' : '') + date.getMinutes() + ':'
  sDate += (date.getSeconds() < 10 ? '0' : '') + date.getSeconds()
  reqObj.timestamp = sDate;
  var keyList = []
  for (key in reqObj) {
    if (key != 'sign')
      keyList.push(key)
  }
  var data = app_secret;
  keyList.sort().forEach(key => {
    data += key + reqObj[key]
  })
  data += app_secret
  reqObj.sign = crypto.createHash("md5").update(data).digest("hex").toUpperCase();
  var sUrl = 'http://gw.api.taobao.com/router/rest?';
  for (key in reqObj) {
    sUrl += key + '=' + reqObj[key] + '&'
  }
  var urlObj = url.parse(sUrl, true),
    options = {
      host: urlObj.hostname,
      port: urlObj.port,
      path: urlObj.pathname,
      method: 'GET'
    }
  if (urlObj.search)
    options.path += urlObj.search.replace(/ /g, '+');
  const req = http.request(options, (res) => {
    var body = []
    res.on('data', (chunk) => {
      body.push(chunk)
    }).on('end', () => {
      var resObj = JSON.parse(Buffer.concat(body).toString());
      if (resObj.tbk_item_info_get_response) {
        item = resObj.tbk_item_info_get_response.results.n_tbk_item[0];
        shopping.pict_url = item.pict_url;
        shopping.zk_final_price = item.zk_final_price;
        shopping.small_images = JSON.stringify(item.small_images.string);
        shopping.title = item.title;
        shopping.volume = item.volume;
        shoppingDao.update(shopping, () => {
          fillShopping(shoppings.slice(1))
        })
      } else {
        log(resObj)
        fillShopping(shoppings.slice(1))
      }
    }).on('error', (err) => {
      log(err)
    })
  });
  req.on('error', (err) => {
    log(err)
  });
  req.end()
}
